package com.project.seckill.controller;

import com.project.seckill.bo.JsonEntity;
import com.project.seckill.constant.CodeMessage;
import com.project.seckill.dao.entity.User;
import com.project.seckill.service.UserService;
import com.project.seckill.util.Md5Util;
import com.project.seckill.util.ResponseHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * Created by yachao on 2018/6/24.
 */
@Slf4j
@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = {"/", "/index", "/home"})
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/login")
    public String login() {
        return "/login";
    }

    @ResponseBody
    @RequestMapping(value = "/action/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JsonEntity<?> loginHandler(@RequestBody User user) {
        Objects.requireNonNull(user, "The information of user cannot be null.");

        String password = user.getPassword();
        User userFromDb = userService.findUserByTelephone(user.getTelephone());
        log.info("inputPassword is {}, md5 is {}, passFromDb is {}", password, Md5Util.inputPassToFormPass(password), userFromDb.getPassword());

        if (Objects.equals(Md5Util.inputPassToFormPass(password), userFromDb.getPassword())) {
            return ResponseHelper.ofNothing();
        }
        return ResponseHelper.error(CodeMessage.TELEPHONE_OR_PASSWORD_ERROR);
    }
}
